<template>
  <el-dialog v-model="visible" :title="isForumTopic ? '选择帖子话题' : '选择动态话题'" width="80%" :before-close="handleClose">
    <!-- 搜索栏 -->
    <div class="handle-box">
      <el-input v-model="searchForm.topicName" placeholder="话题名称" class="handle-input mr10" clearable />
      <!-- <el-select v-model="searchForm.isHot" placeholder="是否热门" class="handle-select mr10" clearable>
        <el-option label="全部" value="" />
        <el-option label="热门" :value="1" />
        <el-option label="普通" :value="0" />
      </el-select> -->
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border class="table" ref="topicTable" header-cell-class-name="table-header"
      @selection-change="handleSelectionChange" row-key="topicId">
      <el-table-column type="selection" width="55" :reserve-selection="true" />
      <el-table-column prop="topicId" label="话题ID" width="100" />
      <el-table-column prop="topicName" label="话题名称" />
      <el-table-column prop="isHot" label="是否热门" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.isHot ? 'danger' : 'info'">
            {{ scope.row.isHot ? '热门' : '普通' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="noteCount" label="关联笔记数" align="center" />
      <el-table-column prop="topicPopularity" label="话题热度" align="center" sortable />
      <el-table-column prop="topicDescription" label="话题描述" min-width="200">
        <template #default="scope">
          <div class="description-cell">
            {{ scope.row.topicDescription || '-' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ scope.row.createTime ? dateFormat(scope.row.createTime) : '-' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selected-info">已选择 {{ selectedTopics.length }} 个话题</span>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import moment from "moment";
import { getTopics, getForumTopics } from "@/api/content";

export default {
  name: "SelectTopic",
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    // 已选中的话题数据
    selectedData: {
      type: Array,
      default: () => []
    },
    // 是否为帖子话题，默认false使用普通话题接口，true使用论坛话题接口
    isForumTopic: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'confirm'],
  data() {
    return {
      searchForm: {
        topicName: "",
        isHot: "",
      },
      tableData: [],
      selectedTopics: [], // 当前选中的话题
      isSettingSelection: false, // 标记是否正在设置选中状态
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.getData();
        this.initSelectedData();
      }
    }
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      if (this.searchForm.topicName) {
        params.topicName = this.searchForm.topicName;
      }
      if (this.searchForm.isHot !== "") {
        params.isHot = this.searchForm.isHot;
      }

      return params;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        // 根据isForumTopic参数选择使用哪个接口
        const response = this.isForumTopic
          ? await getForumTopics(params)
          : await getTopics(params);

        if (response && response.data) {
          this.tableData = response.data.rows || response.data;

          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }

          // 数据加载完成后，设置已选中的数据
          this.$nextTick(() => {
            this.setSelectedRows();
          });
        }
      } catch (error) {
        console.error('获取话题数据失败:', error);
        this.$message.error('获取话题数据失败');
      }
    },
    // 初始化已选中的数据
    initSelectedData() {
      this.selectedTopics = [...this.selectedData];
    },
    // 设置表格中已选中的行
    setSelectedRows() {
      if (this.$refs.topicTable) {
        // 临时禁用选择变化监听
        this.isSettingSelection = true;

        this.$refs.topicTable.clearSelection();

        if (this.selectedTopics.length > 0) {
          this.tableData.forEach(row => {
            const isSelected = this.selectedTopics.some(selected => selected.topicId === row.topicId);
            if (isSelected) {
              this.$refs.topicTable.toggleRowSelection(row, true);
            }
          });
        }

        // 重新启用选择变化监听
        this.$nextTick(() => {
          this.isSettingSelection = false;
        });
      }
    },
    // 处理表格选择变化
    handleSelectionChange(selection) {
      // 如果正在设置选中状态，则忽略这次变化
      if (this.isSettingSelection) {
        return;
      }

      // 获取当前页面中被选中的项
      const currentPageSelected = selection;

      // 获取当前页面中未被选中但之前在其他页面被选中的项
      const otherPageSelected = this.selectedTopics.filter(selected => {
        return !this.tableData.some(row => row.topicId === selected.topicId);
      });

      // 合并选中的数据
      this.selectedTopics = [...otherPageSelected, ...currentPageSelected];
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false;
    },
    // 确认选择
    handleConfirm() {
      this.$emit('confirm', this.selectedTopics);
      this.handleClose();
    }
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.description-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}
</style>